<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            :rules="queryRules"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="年度" :prop="$store.getters.allDefectObj['HR-WEB-181'] == 0 ?'' :'year'">
                <el-input
                    v-model.trim.number="queryParams.year"
                    placeholder="请输入年度"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>


            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="recordList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                ></el-table-column>

                <el-table-column
                    label="考核模板"
                    align="center"
                    prop="modelName"
                />
                <el-table-column label="总分" align="center" prop="score" />
                <el-table-column label="年度" align="center" prop="year" />


            </el-table>

            <pagination
                v-show="total >10 && $store.getters.allDefectObj['HR-WEB-179'] == 1"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改年度考核记录对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1200px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-row>


                        <el-col :span="8">
                            <el-form-item label="岗位" prop="postId">
                                <el-select
                                    v-model="form.postId"
                                    placeholder="请选择岗位"
                                    clearable
                                    @change="setPostId"
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="用户" prop="realName">
                                <el-input
                                    suffix-icon="el-icon-search"
                                    readonly
                                    @focus="openSecelctOneUser"
                                    v-model="form.realName"
                                    placeholder="请选择用户"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="模板名称" prop="modelId">
                                <el-select
                                    v-model="form.modelId"
                                    @change="changeModel"
                                >
                                    <el-option
                                        v-for="item in modelList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="适用日期" >
                                <el-input disabled v-model="form.year" />
                            </el-form-item>
                        </el-col>
                    </el-row>


                        <el-table-column
                            label="序号"
                            align="center"
                            prop="index"
                            width="50"
                        />
                        <el-table-column label="指标名称" prop="name">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.name"
                                    placeholder="请输入指标名称"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="指标描述" prop="describe">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.describe"
                                    placeholder="请输入指标描述"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="考核方向" prop="purpose">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.purpose"
                                    placeholder="请输入考核方向"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="分值" prop="score">
                            <template slot-scope="scope">
                                <el-input-number
                                    :precision="0"
                                    :max="100"
                                    :min="0"
                                    controls-position="right"
                                    v-model="scope.row.score"
                                    placeholder="请输入分值"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <userTableDialog
            title="员工列表"
            :defaultParams="defaultParams"
            :open.sync="showUserTableVision"
            @confirm="setBaseInfo"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listRecord,
    getRecord,
    delRecord,
    addRecord,
    updateRecord,
} from "@/api/hrm/record";
import {
    listAppraise
} from "@/api/person/index";


import { listInductionAll } from "@/api/hrm/staff/induction";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";

import {
    listModel,
    getModel,
    delModel,
    addModel,
    updateModel,
    addRelation,
    delRelation,
} from "@/api/hrm/model";

export default {
    name: "Record",
    data() {
        return {
            //员工信息弹窗
            defaultParams: {
                isLink: true,
                staffTypes:"1,4,5,6"
            },
            showUserTableVision: false,

            //部门
            // 职位选项
            postList: [],
            // 部门树选项
            deptOptions: [],
            deptOptionsArray: null,

            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedHrmAppraiseItemRecord: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 年度考核记录表格数据
            recordList: [],
            // 考核项目记录表格数据
            hrmAppraiseItemRecordList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize:  this.$store.getters.allDefectObj['HR-WEB-179'] == 0  ? 99999: 10,

                isAsc: "descending",
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                year: null,
                score: null,
            },
            // 表单参数
            form: {},
            queryRules:{
                year:[
                //只能是四位数字
                {
                    pattern: /^\d{4}$/,
                    message: '请输入四位数字',
                    trigger: 'blur'
                },
                ],

            },

            // 表单校验
            rules: {

                deptId: [
                    {
                        required: true,
                        message: "请选择部门",
                        trigger: "change",
                    },
                ],
                postId: [
                    {
                        required: true,
                        message: "请选择岗位",
                        trigger: "change",
                    },
                ],
                realName: [
                    {
                        required: true,
                        message: "请选择员工",
                        trigger: "change",
                    },
                ],
                modelId: [
                    {
                        required: true,
                        message: "请选择模板",
                        trigger: "change",
                    },
                ],
            },
            modelList: [],
        };
    },
    components: { Treeselect },
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
        this.getModelList();
    },
    methods: {
        //匹配选中的模板带入考核记录
        changeModel(val) {
            let obj = this.modelList.find((item) => item.id == val);
            this.form.modelName = obj.name;
            this.form.year = obj.year;
            this.hrmAppraiseItemRecordList = obj.items.map((item) => {
                delete item.id;

                return {
                    ...item,
                    describe: item.desc,
                    year: obj.year,
                };
            });
        },
        //获取所有的模板
        getModelList() {
            listModel({ pageNum: 1, pageSize: 100, isAsc: "descending" }).then(
                (response) => {
                    this.modelList = response.rows;
                }
            );
        },

        //查询参数联动
        setDeptId(id) {
            this.defaultParams.orgId = id;
        },
        //查询参数联动
        setPostId(id) {
            this.defaultParams.postId = id;
        },
        //唤醒员工弹窗
        openSecelctOneUser() {
            this.showUserTableVision = true;
        },

        // 设置选中的基础信息
        setBaseInfo(row) {
            this.form.userId = row.userId;
            this.form.realName = row.realName;
            this.form.staffNum = row.staffNum;
            this.form.deptId = row.deptId;
            this.form.orgId = row.orgId;
            if (row.postId) {
                let temp = row.postId.split(",");
                if (temp.length > 0) {
                    this.form.postId = Number(temp[0]);
                }
            }
            this.form.deptName = this.parseSelectTree(this.form.deptId);
            this.form.postName = this.parsePostName(this.form.postId);
        },
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let obj = this.postList.find((item) => item.postId == ids);
                if (obj) {
                    return obj.postName;
                }
            }
            return "—";
        },
        getUserList() {
            listInductionAll({ deptId: this.form.deptId }).then((response) => {
                this.recordList = response.data;
            });
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },

        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        setFormBase(row) {
            let temp = { ...row };
            console.log(temp, "temp");
            // 带入姓名 用户id  部门id 部门 所属岗位
            this.form.deptId = temp.deptId;
            this.form.userId = temp.userId;
            this.form.orgId = temp.orgId;
            this.form.staffNum = temp.staffNum;
            this.form.postId = [];

            if (temp.postId) {
                let tempList = temp.postId.split(",");
                tempList.forEach((item) => {
                    this.form.postId.push(Number(item));
                });
            }

            this.form.sex = temp.sex;
            this.form.staffType = temp.staffType;

            this.form.type = "0";
            this.$set(this.form, "realName", temp.realName);
        },

        /** 查询年度考核记录列表 */
        getList() {
            this.loading = true;
            listAppraise(this.queryParams).then((response) => {
                this.recordList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                year: null,
                score: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
            };
            this.queryParams={} ;
            this.hrmAppraiseItemRecordList = [];
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {

            if(this.$store.getters.allDefectObj['HR-WEB-182'] == 0 )
        {
            return 
        }

            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    this.queryParams.pageNum = 1;
                    this.getList();
                }
            }
            )

        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.queryParams.year = null ;
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加绩效表";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getRecord(id).then((response) => {
                this.form = response.data;
                this.form.deptId = Number(this.form.deptId )
                this.form.postId = Number(this.form.postId)
                this.hrmAppraiseItemRecordList =
                    response.data.hrmAppraiseItemRecordList;
                this.open = true;
                this.title = "修改绩效表";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.hrmAppraiseItemRecordList =
                        this.hrmAppraiseItemRecordList;
                    if (this.form.id != null) {
                        updateRecord(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addRecord(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm("绩效表删除后不可恢复，确认删除？")
                .then(function () {
                    return delRecord(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("已经完成删除！");
                })
                .catch(() => {});
        },
        /** 考核项目记录序号 */
        rowHrmAppraiseItemRecordIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 考核项目记录添加按钮操作 */
        handleAddHrmAppraiseItemRecord() {
            let obj = {};
            obj.name = "";
            obj.describe = "";
            obj.purpose = "";
            obj.score = "";
            obj.year = "";
            this.hrmAppraiseItemRecordList.push(obj);
        },
        /** 考核项目记录删除按钮操作 */
        handleDeleteHrmAppraiseItemRecord() {
            if (this.checkedHrmAppraiseItemRecord.length == 0) {
                this.$modal.msgError("请先选择要删除的考核项目记录数据");
            } else {
                const hrmAppraiseItemRecordList =
                    this.hrmAppraiseItemRecordList;
                const checkedHrmAppraiseItemRecord =
                    this.checkedHrmAppraiseItemRecord;
                this.hrmAppraiseItemRecordList =
                    hrmAppraiseItemRecordList.filter(function (item) {
                        return (
                            checkedHrmAppraiseItemRecord.indexOf(item.index) ==
                            -1
                        );
                    });
            }
        },
        /** 复选框选中数据 */
        handleHrmAppraiseItemRecordSelectionChange(selection) {
            this.checkedHrmAppraiseItemRecord = selection.map(
                (item) => item.index
            );
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "hrm/record/export",
                {
                    ...this.queryParams,
                },
                `record_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
